6 June 2016

Why? Presenting research results

Nature, October 2014

Why? Teaching

Least squares estimation

Linear regression model

\[ y_i = \alpha + \beta x_i + \epsilon \]

Estimates for the intercept and slope can be found by minimizing the squared residuals.

\[ \arg\min_{\alpha, \beta} \sum_i \left(y_i - (\alpha + \beta x_i) \right)^2 \]





Why? Teaching

Why? Teaching

Why? Teaching

Why? Teaching

Slidify

library(shiny)
runGitHub('ekstroem/ShinyLeastSquares')

The "role" of graphics is changing and expanding

Background

Toby

  • Dept. XXX, XXX
  • R packages: animint
  • Some other nice info.
  • Change pic?




Claus

  • Dept. Biostatistics, UCPH
  • R packages: MESS, MethComp, SuperRanker, …
  • R book: The R Primer
  • Happy/frustrated interactive graphics enthusiast

Outline for the tutorial

Topic Time
Introduction 15 minutes
Highlevel interactive graphics (javascript libraries) 35 minutes
Interactive graphics (shiny, ggplotly) 35 minutes
Break
Multi layer/-panel graphics 30 minutes
Animated graphics 30 minutes
Putting it all together 30 minutes

Tutorial goals:

  1. Explain and emphasize the role that interactive graphics have in reporting, scientific journals, and in teaching.
  2. Give overview of existing R packages for interactive graphics.
  3. Explain the strengths and weaknesses of the existing R packages, to highlight directions for future work.

Necessary stuff

Necesary packages etc XXX To be filled out at the end

Rstudio

See also: Toby's link

devtools::install_github("ramnathv/rCharts")

Concepts

Tobys slides terms / discussion

  • multi-layer, multi-panel, multi-plot
  • animation, direct manipulation (clicking, hovering), indirect manipulation (buttons, menus)
  • zoom, highlight, show/hide (data, labels, tooltips)

An example of 1

An example of 2

An example of 3

The role of the graphics/viewer

Interactive graphics architechture

  • Distribution and viewing
  • Dedicated server vs. local server

Javascript-based libraries

R and Javascript architecture

D3.js doesn’t ship with any pre-built charts out of the box. However, go to website to get an overview of the possibilities.

  • ChartJS
  • Chartist.js
  • [n3]
  • plotly

Highlevel interactive graphics

Numerous possibilities in R packages

  • rCharts (oldish - mix of libraries)
  • highcharter (standard plot types, mature library)
  • dygraphs (mostly time series. well documented. Rich features)
  • metricsgraphics (also time series)
  • leaflet (maps)
  • plotly (general plots - like ggplot)
  • htmlwidgets Javascript framework (many are part of this)





  • No standard interface
  • Not easily extendable from R
  • Pick a library and learn it!

rCharts interfaces

polychart (from rCharts)

plot/lattice-like function.

library(rCharts)
library(MESS)
data(happiness)
mydf <- happiness
mydf$size <- sqrt(mydf$population)/8
r1 <- rPlot(x = "tax", 
            y = "happy", 
            data = mydf, 
            type = "point", 
            color = "continent", 
            size = "size")
r1

Type: bar, layers, …

polychart (from rCharts)

plot/lattice-like function. Add layers and guides to plot ..

mydf2 <- data.frame(tax=c(1, 50), 
                happy=c(4.93, 7.09))

r1$layer(x = "tax", 
         y = "happy", 
         data = mydf2, 
         type = "line",
         size=list(const=4))

r1$guides(y = list(title="New label", 
                   min=0, max=12))

r1
  • layer \(\approx\) points/lines
  • guides \(\approx\) axis
  • addParams \(\approx\) title, plot size

polychart - tooltips

r3 <- rPlot(x = "tax", y = "happy", 
      data = mydf, type = "point", 
      color = "continent", 
      size = "size", 
      tooltip="#!function(item){ 
return ('Country: ' +item.country+ 
        '&#013; Tax: ' +item.tax+ 
        '% Happiness: ' +item.happy+
        '<br> Pop: ' +item.population+ 
        ' mio.') }!#")  

Passing javascript is non-trivial.

Highcharts

HighCharter

highcharter

Mature charts, stocks (time series), maps. Good API.

  • Start with empty chart and add components.
  • (Mostly) no default arguments
library(highcharter)
hc <- highchart() %>% 
  hc_chart(type = "column") %>% 
  hc_title(text = "Denmark") %>% 
  hc_xAxis(categories = 2011:2016) %>% 
  hc_add_series(data = c(3806,  6184,  
                         7557, 14792, 
                         21315, 3016),
          name = "Asylum seekers") %>% 
  hc_add_serie(name = "Syria", 
               data = c(429, 822, 
                      1710, 7087, 
                       8608, 777),
               type = "spline")
hc





Highcharter - adding data

Data are added using one of the following functions

Name Function
hc_add_series Add single series (named: data, name)
hc_add_series_list Add list named series
hc_add_series_df Add data.frame. Name variables accordingly
hc_add_series_ts Add ts object. Extra argument: name
hc_add_series_scatter Crate scatter from two vectors. Extra arguments (size, color, label)
hc_add_series_boxplot Add boxplots
hc_add_series_map Add geojson map

Highcharter function overview

| Function | Example | |——–+———-| | Title | hc_title(text = "Temperature") | | Axis | hc_xAxis(categories = month) | | | hc_yAxis(title = list(text = "Temperature"), labels = list(format = "{value}? C")) | | Theme | hc_add_theme(hc_theme_sandsignika()) | | Zoom | hc_chart(zoomType = "xy") | | Tooltip | hc_tooltip(useHTML = TRUE, headerFormat=" ", | | | pointFormat = " " | | | footerFormat = "
x-val {point.x}

") |

Highcharter - adding information

Highcharter - adding information

Highcharter - Happyness and taxes

(replace the one above)

Highcharter function overview

References

dygraph

library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures") %>% 
  dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))

dygraphs 2

metricsgraphics

Should be the same as before (happyness)

Metricgraphics

library(RColorBrewer)

tmp <- data.frame(year=seq(1790, 1970, 10), uspop=as.numeric(uspop))

tmp %>%
  mjs_plot(x=year, y=uspop) %>%
  mjs_point() %>%
  mjs_add_marker(1850, "Something Wonderful") %>%
  mjs_add_baseline(150, "Something Awful")

Metricgraphics

Metricgraphics function overview

leaflet

library(leaflet)
library(MESS)


data(earthquakes)
m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=earthquakes$longitude[earthquakes$mag>6],          lat=earthquakes$latitude[earthquakes$mag>6], popup="Mag 6+")
m

leaflet

leaflet function overview

rMaps - choropleths

    <div class='container'>
      <input id='slider' type='range' min=1960 max=2010 ng-model='year' width=200>
      <span ng-bind='year'></span>
      <div id='chart6b435311e410' class='rChart datamaps'></div>          
    </div>
    <script>
      function rChartsCtrl($scope){
        $scope.year = 1960;
        $scope.$watch('year', function(newYear){
          mapchart6b435311e410.updateChoropleth(chartParams.newData[newYear]);
        })
      }
   </script>

Publishing interactive graphics

html output. Need javascript machinery to run.

saveWidget()

self_contained: false

html

standalone

javascript

images

Including in R markdown

savewidget iframe

Exercise

Shiny and plotly

plotly + ggplotly

Differences to other libraries … public

ggplotly - ggplot2

Exercise

ggiraph

Shiny

Use standard R. Rather simple and beautiful. Simple input - no fancy transitions. Requires server

Example

library(shiny)
runGitHub('ekstroem/ShinySampleMean')

Quick introduction to Shiny

Shiny User Interface

Shiny server interface

Example

ui.R

server.R

Building the user interface

User interface functions

Example -> product

Building the server side

Server side functions

Example -> product

Finished product

ui.R

server.R

Running apps

Running apps from Github

Exercise

Remember

High-level interactive plotting packages, 30 minutes • Simple approaches like rotating plots (rgl package) and simple user interaction (wallyplot from MESS package). • Interactive bar plots (rCharts, several different JavaScript interfaces, interfacing with JavaScript libraries to change axes and legends) • Interactive scatter plots showing happiness and tax rate (rCharts, and clickme packages, several different JavaScript interfaces, add dropdown effects and improve tooltips) • interactive maps and choropleths (the rMaps packages) • Discussion of frustrations that new users unfamiliar with JavaScript may encounter when interfacing with JavaScript libraries

Interactive graphics with shiny and plotly, 30 minutes • Teaching least squares estimation (shiny) • Teaching power calculations (shiny) • Reproducing some of the previous graphics on happiness and tax rate in plotly (ggplot2, and ggplotly, adding tooltips/hover effects, and dropdown) • Graphics on prediction accuracy for Danish population predictions (plotly, adding sliders)